package com.fly.lambda.service;

import com.fly.lambda.dao.AccountDAO;
import com.fly.lambda.domain.Account;
import com.fly.lambda.framework.context.ContextHolder;
import com.fly.lambda.framework.utils.CommonUtils;
import com.fly.lambda.framework.utils.MD5Util;
import com.fly.lambda.framework.web.session.AccountSession;
import com.fly.lambda.framework.web.session.SessionManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Fly on 2016/7/19.
 */
@Service
public class LoginService {

    @Autowired
    AccountDAO accountDAO;
    @Autowired
    SessionManage sessionManage;

    /**
     * 管理员账号登录
     * @param response
     * @param loginName     用户名
     * @param password      密码
     * @return 登录是否成功， true: 成功, false: 失败
     */
    @Transactional
    public boolean login(HttpServletResponse response, String loginName, String password){
        boolean result = false;
        Account account = accountDAO.queryByLoginNameAndPwd(loginName, MD5Util.GetMD5Code(password));
        if (null != account){

            //账号存在，生成cookie
            AccountSession accountSession = new AccountSession();
            accountSession.setSessionId(CommonUtils.genPK());
            accountSession.setAccountId(account.getAccountId());
            accountSession.setLoginName(account.getLoginName());
            sessionManage.setAccountSession(response, accountSession);
            //sessionId保存到context
            ContextHolder.setAccountId(account.getAccountId());

            result = true;
        }
        return result;
    }

    public void logout(HttpServletResponse response, HttpServletRequest request){
        sessionManage.removeAccountSession(response);
    }

}
